import { StoreService } from './../../../service/store.service';
import { NavigateService } from './../../../service/navigate.service';
import { MdSnackBar } from '@angular/material';
import { OrderComboDetailService } from './orderComboDetail';
import { MdDialog, MdDialogRef, MdDialogConfig } from "@angular/material";
import { ComboItem } from './../../../model/clerkDataContext';
import { InventoryService } from './../../../service/inventory.service';
import { RemarkService } from './../../../component/primeng/remark/remark.module';
import { CacheManager } from './../../../common/cacheManager';
import { Component, OnInit, Input, trigger, state, style, transition, animate, ElementRef, AfterViewInit, OnDestroy, OnChanges, Output, SimpleChange, EventEmitter } from '@angular/core';
import { ObjectCopier } from "../../../common/objectCopier";
import { Inventory, Modifier, Cart } from "../../../model/clerkDataContext";
import { CartService } from "../../../service/index";
import { MessageBoxService, GrowlMessageType, MessageResult } from "../../../component/index";
import { aovidDoubleClick } from "./../../../component/decorators";

export class OrderMoreService {
    private tmp: OrderMore;
    static Current: OrderMoreService = new OrderMoreService();
    dialogRef: MdDialogRef<OrderMore>;
    config: MdDialogConfig = {
        disableClose: false,
        width: '100%',
        position: {
            top: '0',
            bottom: '',
            left: '',
            right: ''
        }
    }
    constructor() { }
    Regist(tmp: OrderMore) {
        this.tmp = tmp;
    }
    /**
     * @param  {Inventory} inventory   当前商品
     * @param  {Cart} cartItem    当前购物车项
     * @param  {Modifier[]} commonMods   通用商品选项
     * @param  {boolean} require  是包含商品必选项
     */
    Open(dialog: MdDialog, cartItem: Cart, commonMods: Modifier[], require?: boolean): Promise<Cart> {
        this.dialogRef = dialog.open(OrderMore, this.config);
        let inventory = cartItem.inventory;
        this.tmp.Inventory = inventory;
        this.tmp.description = cartItem.extended ? cartItem.extended.description : '';
        this.tmp.cartItem = cartItem;
        this.tmp.cartItem.modifiers = cartItem.modifiers ? cartItem.modifiers : { amount: 0, items: [] };
        this.tmp.ModifierList = [];
        this.tmp.Qty = cartItem.qty;
        this.tmp.combo = [];
        this.tmp.require = require;
        this.tmp.commonMods = <any>ObjectCopier.Copy(commonMods);

        if (inventory.combo && inventory.combo.group && inventory.combo.group.length) {
            this.tmp.combo = <any>ObjectCopier.Copy(inventory.combo);
            this.initSelectCombo(cartItem, inventory);
        }
        let mods = commonMods.filter(m => {
            if (!m.applyCategories || !m.applyCategories.length) {
                return true;
            } else {
                let boo = false;
                for (let cat of m.applyCategories) {
                    let r = inventory.categories.filter(ca => { return ca.id == cat.id });
                    if (r && r.length) {
                        boo = true;
                        break;
                    }
                }
                return boo;
            }
        });
        let mlist = this.ReLoadCheckedModifiy(inventory.modifiers, cartItem, mods);
        mlist.forEach(x => {
            this.tmp.ModifierList.push(ObjectCopier.Copy<Modifier>(x));
        });
        //必选项排在前面
        this.tmp.ModifierList.sort(m => {
            if (m.isRequired) {
                return -1;
            } else {
                return 1;
            }
        });
        return new Promise((resolve, reject) => {
            this.dialogRef.afterClosed().subscribe(invt => {
                this.dialogRef = null;
                resolve(invt);
            });
        });
    }

    /**
     * 选中已选中的商品选项
     */
    private ReLoadCheckedModifiy(mList: Modifier[], cartItem: Cart, commonMods: Modifier[]): Modifier[] {
        let result: Modifier[] = [];
        if (!mList || !mList.length) {
            mList = [];
        }
        result = mList.concat(commonMods);
        result.forEach(item => {
            item.options.forEach(element => {
                delete element.selected;
            });
        });
        if (cartItem.modifiers && cartItem.modifiers.items.length) {
            cartItem.modifiers.items.forEach(x => {
                let m = result.find(n => n.id == x.id);
                x.options.forEach(opt => {
                    let oo = m.options.find(nn => nn.name == opt.name);
                    if (oo && opt.selected) {
                        oo.selected = true
                    };
                });
            });
        } else {
            //选中设置了默认选中的商品选项
            result.forEach(item => {
                item.options.forEach(element => {
                    if (element.checked) {
                        element.selected = true;
                    };
                });
            });
        }
        return result;
    }
    /**
     * 初始化已选中的套餐项
     */
    private initSelectCombo(cartItem, inventory) {
        if (cartItem.extended && cartItem.extended.combo && inventory.combo) {
            for (let group of cartItem.extended.combo.group) {
                let targetGroup = (<any>this.tmp.combo).group.find(gro => { return gro.id == group.id; });
                if (targetGroup) {
                    for (let item of group.items) {
                        let targetItem = targetGroup.items.find(it => { return it.id == item.inventoryId; });
                        if (targetItem) {
                            if (!group.choiceQty && !item.extended.description && (!item.modifiers || !item.modifiers.items || !item.modifiers.items.length)) {
                                continue;
                            }
                            targetItem.selectOption = targetItem.selectOption ? targetItem.selectOption : [];
                            let itemObj = <any>{};
                            itemObj.description = item.extended.description;
                            itemObj.modifiers = item.modifiers;
                            itemObj.price = item.price;
                            itemObj.qty = item.qty / targetItem.qty;
                            if (group.choiceQty) {
                                targetItem.selectQty = targetItem.selectQty ? targetItem.selectQty : 0;
                                targetItem.selectQty += itemObj.qty;
                            }
                            targetItem.amount = (item.modifiers && item.modifiers.amount) ? item.modifiers.amount : 0;
                            targetItem.selectOption.push(itemObj);
                        }
                    }
                }
            }
        }
    }
}

@Component({
    //moduleId: module.id,
    selector: 'div[order-more]',
    template: `
        <md-dialog-content fxLayout="column" class="order-more-content">
            <header class="app-header noshrink header-dark">
                <span id="dialog-back-btn" class="i-arrow-back margin-l header-icon" (click)="cancel()"></span>
                <span fxFlex="100%" class="margin-l-xs">{{Inventory?Inventory.name:''}}</span>
                <span class="margin-r header-confirm" (click)="ok()">确定</span>
            </header>
            <div tabindex="0" autofocus fxLayout="column" fxFlex="100%" class="order-detail pct100 v-scroll">
                <div fxLayout="column">
                    <div *ngIf="combo && combo.group && combo.group.length">
                        <div *ngFor="let group of combo.group">
                            <div *ngIf="group.choiceQty">
                                <div class="order-more-class" fxLayout="row" fxLayoutAlign="center center">
                                    <div class="padding-l-s" fxFlex="100%">
                                        <span>{{group.name}}</span>
                                        <span>（</span>
                                        <span>{{group.items.length}}选{{group.choiceQty}}</span>
                                        <span>）</span>
                                    </div>
                                </div>
                                <div fxLayout="column">
                                    <div class="combo-list" fxLayout="column" fxLayoutAlign="start center" *ngFor="let item of group.items">
                                        <div class="combo-order pct100" fxLayout="row" fxLayoutAlign="start center">
                                            <div fxLayout="row" fxLayoutAlign="start center" class="padding-l-s h100 text-s" fxFlex="100%" (click)="updateModInfo(item, group)">
                                                <span class="combo-order-name">{{item.name}}</span>
                                                <span class="color-primary noshrink" *ngIf="item.plusPrice != undefined">{{"(+" + (item.plusPrice | number: '1.2-2' | currencySymbol) + ")"}}</span>
                                                <!--<span *ngIf="item.selectQty">x{{item.selectQty * item.qty}}</span>-->
                                            </div>
                                            <div fxLayout="row" fxLayoutAlign="center center" class="combo-btn combo-btn-photos noshrink" *ngIf="item.selectQty > 0 && isShowCartBtn(group)" (click)="onComboCheck(item, group, $event)">
                                                <span class="i-add-to-photos text-s"></span>
                                            </div>
                                            <div fxLayout="row" fxLayoutAlign="center center" class="combo-btn" *ngIf="item.selectQty==1 && !(checkComboOption(item))" (click)="onComboDelete(item, group, $event)">
                                                <span class="icon-delete-circle-o"></span>
                                            </div>
                                            <div fxLayout="row" fxLayoutAlign="center center" class="combo-btn" *ngIf="item.selectQty>1 && !(checkComboOption(item))" (click)="onComboMinus(item, group, $event)">
                                                <span class="icon-minus-circle-o"></span>
                                            </div>
                                            <div fxLayout="row" fxLayoutAlign="center center" class="combo-btn" *ngIf="!item.selectQty && !(checkComboOption(item))" (click)="onComboCheck(item, group, $event)">
                                                <span class="icon-check-circle-o"></span>
                                            </div>
                                            <div class="combo-btn-qty noshrink" fxLayout="row" fxLayoutAlign="center center" *ngIf="item.selectQty > 0 && !(checkComboOption(item))">{{item.selectQty}}</div>
                                            <div fxLayout="row" fxLayoutAlign="center center" class="combo-btn combo-btn-add" *ngIf="item.selectQty>0 && !(checkComboOption(item))" (click)="onComboAdd(item, group, $event)">
                                                <span class="i-add-circle"></span>
                                            </div>
                                        </div>
                                        <div class="pct100" *ngIf="checkSelectOption(item)">
                                            <div class="combo-select-option" fxLayout="row" *ngFor="let opt of item.selectOption;let index = index">
                                                <div class="combo-option-order">
                                                    <span *ngIf="checkComboOption(item)">#{{index+1}}</span>
                                                </div>
                                                <div fxFlex="100%" (click)="updateSelectOption(item, index, group.choiceQty)">
                                                    <div fxLayout="row" fxLayoutWrap="wrap">
                                                        <div fxLayout="row" fxLayoutWrap="wrap" *ngIf="opt.modifiers && opt.modifiers.items && opt.modifiers.items.length">
                                                            <div fxLayout="row" fxLayoutWrap="wrap" *ngFor="let item of opt.modifiers.items">
                                                                <div class="tag noshrink" *ngFor="let option of item.options">
                                                                    <span>{{option.name}}</span>
                                                                    <span *ngIf="option.price">（{{option.price|currencySymbol}}）</span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="tag noshrink" *ngIf="opt.description">
                                                            <span>{{opt.description}}</span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div fxLayout="row" fxLayoutAlign="center start" class="noshrink" *ngIf="checkComboOption(item)">
                                                    <div fxLayout="row" fxLayoutAlign="center center" class="combo-btn" *ngIf="opt.qty==1" (click)="deleteSelectOption(opt, item, group, index, $event)">
                                                        <span class="icon-delete-circle-o"></span>
                                                    </div>
                                                    <div fxLayout="row" fxLayoutAlign="center center" class="combo-btn" *ngIf="opt.qty>1" (click)="minusSelectOption(opt, item, group, $event)">
                                                        <span class="icon-minus-circle-o"></span>
                                                    </div>
                                                    <div class="combo-btn-qty noshrink" fxLayout="row" fxLayoutAlign="center center" *ngIf="opt.qty > 0">{{opt.qty}}</div>
                                                    <div fxLayout="row" fxLayoutAlign="center center" class="combo-btn i-add-circle combo-btn-add" (click)="addSelectOption(opt, item, group, $event)"></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div *ngIf="!group.choiceQty">
                                <div class="order-more-class" fxLayout="row" fxLayoutAlign="center center">
                                    <div class="padding-l-s" fxFlex="100%">
                                        <span>{{group.name}}</span>
                                    </div>
                                </div>
                                <div fxLayout="column">
                                    <div fxLayout="column" fxLayoutAlign="center center" *ngFor="let item of group.items">
                                        <div fxLayout="row" fxLayoutAlign="start center" class="pct100 padding-l-s select-qty-item" (click)="updateModInfo(item, group)">
                                            <div fxFlex="100%">
                                                <span>{{item.name}}</span>
                                                <span>x{{item.qty}}</span>
                                            </div>
                                        </div>
                                        <div fxLayout="row" class="pct100 padding-l-s border-bottom combo-select-option" *ngIf="item.selectOption && item.selectOption.length">
                                            <div class="pct100" *ngFor="let opt of item.selectOption">
                                                <div fxLayout="row" fxLayoutWrap="wrap" fxLayoutAlign="start center" *ngFor="let item of opt.modifiers.items">
                                                    <div *ngFor="let option of item.options">
                                                        <div class="tag">
                                                            <span>{{option.name}}</span>
                                                            <span *ngIf="option.price">（{{option.price|currencySymbol}}）</span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div fxLayout="row" fxLayoutWrap="wrap" fxLayoutAlign="start center">
                                                    <div class="tag" *ngIf="opt.description">
                                                        <span>{{opt.description}}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div fxLayout="column">
                        <div *ngFor="let item of ModifierList">
                            <div fxLayout="row" fxLayoutAlign="start center" class="order-more-class padding-l-s">
                                <div>
                                    {{item.name}}
                                    <span class="color-primary" *ngIf="item.isRequired">*</span>
                                </div>
                                <div class="margin-l-s">
                                    {{item.singleton?'可选一项':'可选多项'}}
                                </div>
                            </div>
                            <div class="order-more-option" fxLayout="row" fxLayoutAlign="space-between start" fxLayoutWrap="wrap">
                                <div class="order-more-optitem text-s v-gap" fxLayout="row" fxFlex="48%" fxLayoutAlign="center center" *ngFor="let opt of item.options" (click)="onSelectModifiers(item,opt)" [ngClass]="{'opt-selected': opt.selected}">
                                    <span>{{opt.name}}</span>
                                    <span *ngIf="opt.price > 0">({{opt.price | number:'1.0-2' | currencySymbol}})</span>
                                </div>
                            </div>
                        </div>
                        <div class="order-more-textarea padding-s noshrink" fxLayout="row" fxLayoutAlign="center center">
                            <textarea class="text-s color-lightgray padding-xs" placeholder="请输入备注信息" [(ngModel)]="description"></textarea>
                        </div>
                        <div class="padding-s" fxLayout="row" fxLayoutWrap="wrap" *ngIf="commonRemarks && commonRemarks.length">
                            <div class="tag-plus" *ngFor="let remark of commonRemarks" (click)="selectComRemark(remark)">
                                <span>{{remark.content}}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </md-dialog-content>
        `,
    styleUrls: ['../order.component.scss']
})
export class OrderMore implements OnInit {
    Qty: number;
    Inventory: Inventory;
    ModifierList: Modifier[] = [];
    combo = <any>{};
    description: string;
    cartItem: Cart;
    commonMods: Modifier[] = [];
    require: boolean;
    showComboDetail: boolean = false;
    snackBarRef = null;
    commonRemarks: string[];
    constructor(
        private cartSvr: CartService,
        private msgSvr: MessageBoxService,
        private invtSvr: InventoryService,
        public dialogRef: MdDialogRef<OrderMore>,
        private dialog: MdDialog,
        public snackBar: MdSnackBar,
        private navSvr: NavigateService,
        private storeSvr: StoreService
    ) {
        OrderMoreService.Current.Regist(this);
    }

    @Output() onRemove: EventEmitter<Inventory> = new EventEmitter<Inventory>();

    ngOnInit() {
        this.navSvr.registGoBack(this.goBack);
        this.getPreRemark();
    }

    goBack() {
        let backBtn = document.getElementById("dialog-back-btn");
        if (backBtn) {
            backBtn.click();
        }
    }

    //选中商品选项
    onSelectModifiers(modifier, option) {
        if (option.selected) {
            delete option.selected;
            return;
        }
        if (modifier.singleton) {
            //单选
            modifier.options.forEach(ii => delete ii.selected);
        }
        option.selected = !option.selected;
    }

    async getPreRemark() {
        let remarks = await this.storeSvr.getStoreConfigs("order.process.note");
        if (remarks) {
            this.commonRemarks = remarks;
        } else {
            this.commonRemarks = null;
        }
    }

    //备注
    async openRemark() {
        let rem = await RemarkService.Current.open(this.dialog, this.description);
        if (rem) {
            this.description = <any>rem;
        }
    }
    selectComRemark(remark){
        if (this.description && this.description.length) {
            this.description += ("," + remark.content);
        } else {
            this.description = remark.content;
        }
    }
    //删除商品
    onComboDelete(item, group, event) {
        let opt = item.selectOption[0];
        this.deleteSelectOption(opt, item, group, 0, event);
    }

    //减少商品数量
    onComboMinus(item, group, event) {
        let opt = item.selectOption[0];
        this.minusSelectOption(opt, item, group, event);
    }

    //选中套餐商品
    @aovidDoubleClick()
    async onComboCheck(item, group, event) {
        try {
            event.stopPropagation();
            let allQty = 0;
            for (let value of group.items) {
                if (value.selectQty) {
                    allQty += value.selectQty;
                }
            }
            if (allQty >= group.choiceQty) {
                if (!this.snackBarRef) {
                    this.snackBarRef = this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "【" + group.name + "】的商品数量最大可选" + group.choiceQty);
                    this.snackBarRef.afterDismissed().subscribe(() => {
                        this.snackBarRef = null;
                    });
                }
                return;
            }
            let invt = await this.invtSvr.GetInventoryById(item.id);
            if (invt) {
                if (!item.selectOption || !item.selectOption.length) {
                    item.selectOption = [];
                }
                let require = this.invtSvr.hasRequire(invt, this.commonMods);
                if (require) {
                    let result: any = await OrderComboDetailService.Current.open(this.dialog, invt, this.commonMods);
                    this.navSvr.registGoBack(this.goBack);
                    if (!result) {
                        return;
                    }
                    item.amount = result.modifiers.amount;
                    result.qty = 1; //新增时初始数量为1
                    item.selectOption.push(result);
                } else {
                    let optionObj = {
                        qty: 1,
                        modifiers: null,
                        description: ""
                    }
                    item.selectOption.push(optionObj);
                }
            }
            if (!item.selectQty || item.selectQty < 1) {
                item.selectQty = 1;
            } else {
                item.selectQty++;
            }
            this.checkIsOver(group);
        } catch (error) {
            console.log("ERROR:", error);
        }
    }

    //增加商品数量
    onComboAdd(item, group, event) {
        let opt = item.selectOption[0];
        this.addSelectOption(opt, item, group, event);
    }

    /**
     * 套餐中的商品选项数量加一
     * @param {any} opt  商品具体选项
     * @param {any} item 当前的商品
     */
    addSelectOption(opt, item, group, event) {
        event.stopPropagation();
        let baseQty = group.choiceQty;
        let num = 0;
        if (!baseQty) {
            return;
        }
        if (opt && opt.qty > 0) {
            opt.qty++;
            item.selectQty++;
            let boo = this.checkIsOver(group);
            if (boo) {
                if (!this.snackBarRef) {
                    this.snackBarRef = this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "商品数量超过");
                    this.snackBarRef.afterDismissed().subscribe(() => {
                        this.snackBarRef = null;
                    });
                }
                opt.qty--;
                item.selectQty--;
                return;
            }
        }
    }

    /**
     * 套餐中的商品选项数量加一
     * @param {any} opt  商品具体选项
     * @param {any} item 当前的商品
     */
    minusSelectOption(opt, item, group, event) {
        event.stopPropagation();
        if (opt && opt.qty > 1) {
            // this.isShowCartBtn = true;
            opt.qty--;
            item.selectQty--;
        }
    }

    /**
     * 套餐中的商品选项数量加一
     * @param {any} opt  商品具体选项
     * @param {any} item 当前的商品
     */
    deleteSelectOption(opt, item, group, index, event) {
        event.stopPropagation();
        if (opt && opt.qty) {
            if (item.selectOption.length == 1) {
                delete item.selectOption;
            } else {
                item.selectOption.splice(index, 1);
            }
            item.selectQty--;
        }
    }

    @aovidDoubleClick()
    async updateSelectOption(item, index, choiceQty?) {
        try {
            let invt = await this.invtSvr.GetInventoryById(item.id);
            if (invt) {
                let result: any = {};
                if (choiceQty) { //可选套餐
                    result = await OrderComboDetailService.Current.open(this.dialog, invt, this.commonMods, item.selectOption[index]);
                    this.navSvr.registGoBack(this.goBack);
                    if (result) {
                        item.amount = result.modifiers.amount;
                        item.selectOption[index].modifiers = result.modifiers;
                        item.selectOption[index].description = result.description;
                    }
                } else {  //默认数量套餐
                    if (!item.selectOption) {
                        item.selectOption = [];
                    }
                    result = await OrderComboDetailService.Current.open(this.dialog, invt, this.commonMods, item.selectOption[0]);
                    this.navSvr.registGoBack(this.goBack);
                    if (result) {
                        item.selectOption = [];
                        item.amount = result.modifiers.amount;
                        item.selectOption.push(result);
                    }
                }
            }
        } catch (error) {
            console.log("ERROR:", error);
        }
    }

    @aovidDoubleClick()
    updateModInfo(item, group) {
        if ((!item.selectOption || !item.selectOption.length) && group.choiceQty) {
            return;
        }
        if (item.selectOption && item.selectOption.length > 1 && group.choiceQty) {
            return;
        }
        this.updateSelectOption(item, 0, group.choiceQty);
    }

    /**
     * 检测商品数量是否超过
     */
    private checkIsOver(group) {
        if (!group.items || !group.items.length) {
            return false;
        }
        let amountNum = 0;
        for (let item of group.items) {
            let num = item.selectQty ? item.selectQty : 0;
            amountNum += num;
        }
        return amountNum > group.choiceQty;
    }

    /**
     * 判断是否显示添加新的一项到购物车的按钮
     */
    isShowCartBtn(group) {
        let amountNum = 0;
        for (let item of group.items) {
            let num = item.selectQty ? item.selectQty : 0;
            amountNum += num;
        }
        if (amountNum >= group.choiceQty) {
            return false;
        }
        return true;
    }

    //确认选中信息，关闭dialog
    async ok() {
        //判断套餐数量是否选择正确
        let comboFlag = this.checkComboQty();
        if (!comboFlag) {
            return;
        }
        let mList = this.getSelectedModifier(this.ModifierList);
        let mustSelect = this.checkRequireMod(mList);
        if (mustSelect) {
            if (!this.snackBarRef) {
                this.snackBarRef = this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "【" + mustSelect.name + "】为必选项");
                this.snackBarRef.afterDismissed().subscribe(() => {
                    this.snackBarRef = null;
                });
            }
            return;
        }
        //获取选中的套餐
        let checkedCombo = await this.getSelectedCombos();
        if (checkedCombo) {
            this.cartItem.extended.combo = checkedCombo.comboObj;
            //偏好一致,更新数量和价格
            this.cartItem.price = this.cartItem.inventory.price + checkedCombo.plusPrice + checkedCombo.modPrice;
        }
        //偏好一致,更新数量和价格
        this.cartItem.qty = this.Qty;
        this.cartItem.amount = (this.Qty * this.cartItem.price);
        mList.forEach(element => {
            element.options.forEach(item => {
                if (item.selected && item.price) {
                    this.cartItem.amount += (item.price * this.Qty);
                }
            });
        });
        this.cartItem.modifiers.items = mList;
        this.calcModifierAmount();
        this.cartItem.extended.description = this.description;

        if (this.cartItem.modifiers && this.cartItem.modifiers.items && this.cartItem.modifiers.items.length) {
            this.cartItem.extended.singleModifier = this.cartItem.modifiers.amount;
            this.cartItem.extended.oldAmount = this.cartItem.price * this.cartItem.qty;
        }
        this.dialogRef.close(this.cartItem);
    }

    /**
     * 计算商品选项的价格
     */
    calcModifierAmount() {
        let allAmount = 0;
        for (let item of this.cartItem.modifiers.items) {
            let amount = 0;
            for (let opt of item.options) {
                amount += opt.price ? opt.price : 0;
            }
            item.amount = amount;
            allAmount += amount;
        }
        this.cartItem.modifiers.amount = allAmount;
    }

    /**
     * 当时套餐时，判断选择的商品是否符合选择规定
     */
    private checkComboQty() {
        let flag = true;
        if (this.combo && (<any>this.combo).group && (<any>this.combo).group.length) {
            for (let value of (<any>this.combo).group) {
                if (!value.choiceQty) {
                    continue;
                }
                let baseQty = value.choiceQty;
                let currentQty = 0;
                value.items.forEach(element => {
                    if (element.selectQty) {
                        currentQty += element.selectQty;
                    }
                });
                if (baseQty != currentQty) {
                    if (!this.snackBarRef) {
                        this.snackBarRef = this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "商品【" + value.name + "】商品数量选择不够");
                        this.snackBarRef.afterDismissed().subscribe(() => {
                            this.snackBarRef = null;
                        });
                    }
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }

    /**
     * 获得选中的商品选项
     * @param  {Modifier[]} mlist
     */
    private getSelectedModifier(mlist: Modifier[]): Modifier[] {
        let result: Modifier[] = [];
        mlist.forEach(x => {
            let opts: any[] = [];
            x.options.forEach(n => { if (n.selected) opts.push(n); });
            if (opts && opts.length > 0) {
                let m = ObjectCopier.Copy<Modifier>(x);
                m.options = opts;
                result.push(m);
            }
        });

        return result;
    }

    /**
     * 检查商品必选项是否选中
     * @param  {Modifier[]} selectMod
     */
    private checkRequireMod(selectMod: Modifier[]) {
        let mustMod = null
        for (let mod of this.ModifierList) {
            if (mod.isRequired) {
                let selected = selectMod.find(x => { return x.id == mod.id });
                if (!selected) {
                    mustMod = mod;
                }
            }
        }
        return mustMod;
    }

    //获得选中的套餐商品并重新赋值
    private async getSelectedCombos(): Promise<{ comboObj: any; plusPrice: number; modPrice: number }> {
        let comboObj = {
            group: []
        }
        let result = {
            comboObj: comboObj,
            plusPrice: 0,
            modPrice: 0
        }
        if (this.combo && Array.isArray((<any>this.combo).group) && (<any>this.combo).group.length) {
            try {
                for (let gro of (<any>this.combo).group) {
                    let group = <any>{};
                    let totalSelectQty = 0;
                    let groupItems = [];
                    for (let item of gro.items) {
                        if (item.selectQty > 0 || !gro.choiceQty) {
                            if (item.selectQty && gro.choiceQty) {
                                totalSelectQty += item.selectQty;
                            }
                            let invt = await this.invtSvr.GetInventoryById(item.id);
                            let obj = <any>{};
                            if (item.selectOption && item.selectOption.length) {
                                for (let option of item.selectOption) {
                                    obj = this.invtSvr.buildCombo(invt, item, option);
                                    if (obj.plusPrice && gro.choiceQty) {
                                        result.plusPrice = result.plusPrice ? result.plusPrice : 0;
                                        result.plusPrice += (obj.plusPrice * item.selectQty);
                                    }
                                    groupItems.push(obj);
                                }
                            } else {
                                obj = this.invtSvr.buildCombo(invt, item);
                                if (obj.plusPrice && gro.choiceQty) {
                                    result.plusPrice = result.plusPrice ? result.plusPrice : 0;
                                    result.plusPrice += (obj.plusPrice * item.selectQty);
                                }
                                groupItems.push(obj);
                            }
                        }
                        //计算子商品的商品选项的加价
                        if (item.amount) {
                            if (gro.choiceQty) {
                                result.modPrice += item.amount * (item.selectQty ? item.selectQty : 0);
                            } else {
                                result.modPrice += item.amount;
                            }
                            delete item.amount;
                        }
                    }
                    if (gro.choiceQty) {
                        group.choiceQty = gro.choiceQty;
                        group.totalSelectQty = totalSelectQty;
                    }
                    group.id = gro.id
                    group.name = gro.name;
                    group.items = groupItems;
                    comboObj.group.push(group);
                }
                result.comboObj = comboObj;
                return result;
            } catch (error) {
                console.log("ERROR:", error)
            }
        }
        return null;
    }

    //关闭dialog，不做操作
    cancel() {
        this.dialogRef.close(null)
    }

    /**
     * 当前套餐如果超过两项，或者有备注信息、商品选项，需要额外显示
     */
    private checkComboOption(item) {
        let flag = false;
        if (!item.selectOption || !item.selectOption.length) {
            return flag;
        }
        if (item.selectOption && item.selectOption.length) {
            if (item.selectOption.length > 1) {
                return flag = true;
            }
        }
        return flag;
    }

    private checkSelectOption(item) {
        if (item.selectOption && item.selectOption.length == 1) {
            let opt = item.selectOption[0];
            if (opt.modifiers && opt.modifiers.items && opt.modifiers.items.length) {
                return true;
            }
            if (opt.description) {
                return true;
            }
            return false;
        }
        return true;
    }
}